<?php

/*
	Class: Commerce_Magento_Membership

	About: Author
		Jaybill McCarthy and Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
class CommerceMagentoMembership extends Commerce_Db_Model_Magento {

	// /* Group: Constructors */
	// 
	// /*
	// 	Constructor: __construct
	// 		Calls the parent constructor.
	// 
	// 	Arguments:
	// 		logger (optional) - A Zend logger.
	// */
	// function __construct($customer_session_id = null) {
	//     	return parent::__construct($customer_session_id = null);
	// }

	/* Group: Instance Methods */

	/*
		Function: getCustomerByEmail
			Gets a Magento customer based on their email address.

		Arguments:
			email - The email address of the customer to find.

		Returns:
			TBD
	*/
	function getCustomerByEmail($email) {
		try {
			$this->initSoap();
			$result = $this->client->call($this->_api_session_id, 'customer.list', array(array('email' => $email)));
			if (count($result) > 0) {
				return $result[0];
			}
		} catch (Exception $e) {
dd($e);
		}
	}

	/*
		Function: getCustomerIdByUsername
			Gets a customer's ID for Magento using their Communitas username. Uses <getCustomerByEmail>.

		Arguments:
			username - The username (string) to look for.

		Returns:
			The Magento customer ID for the given Communitas username.

		See Also:
			- <getCustomerByEmail>
	*/
	function getCustomerIdByUsername($username) {
		$customer_id = null;
		$users_table = new Users();
		$user = $users_table->fetchByUsername($username);
		if (!is_null($user)) {
			$customer = $this->getCustomerByEmail($user->email);
			if (!is_null($customer) && is_array($customer)) {
				if (array_key_exists('customer_id', $customer)) {
					return $customer['customer_id'];
				} elseif (array_key_exists('entity_id', $customer)) {
					return $customer['entity_id'];
				} else {
					// TODO - return an error
					return null;
				}
			} else {
				// TODO - return an error
				return null;
			}
		}
	}

	/*
		Function: loginCustomer
			Logs a Communitas user into Magento. Useful for a situation where single-sign-on is desired.

		Arguments:
			email - The customer's email address in Communitas and Magento (they should always be the same).
			password - The customer's Magento password (should be the same as Communitas).

		Returns:
			A valid Magento session ID, or null if there were errors.
	*/
	function loginCustomer($email, $password) {
		$session_id = null;
		// perform magento login and get session ID
		try {
			$this->initSoap();
			$session_id = $this->client->call($this->_api_session_id, 'customer.login', array($email, $password));
		} catch (Exception $e) {
		    // internal exception
dd($e);
    		// $this->logger->report('Exception magento login', $e, Zend_Log::ERR);
		}
		// $this->logger->report('Logged user ' . $email . ' into magento with session id ' . $session_id, null, Zend_Log::INFO);
		return $session_id;
	}

	/*
		Function: logoutCustomer
			Logs out a customer from Magento.

		Arguments:
			session_id - The Magento session ID to log out.

		Returns:
			void
	*/
	function logoutCustomer($session_id) {
		try {
			$this->initSoap();
			return $this->client->call($this->_api_session_id, 'customer.logout', array());
		} catch (Exception $e) {
dd($e);
		}
	}

	/*
		Function: updateCustomer
			Updates customer data in the Magento database for a particular customer.

		Arguments:
			customer_id - The Magento ID of the customer to update.
			first - The new first name for the customer.
			last - The new last name for the customer.
			email - The new email address for the customer.
			password - The new password for the customer.

		Returns: boolean
	*/
	function updateCustomer($customer_id, $first, $last, $email, $password) {
		$customer = array(
	    	'firstname'  => $first,
	    	'lastname'   => $last,
	    	'email'      => $email,	   		   		
		);
		if(!is_null($password)){
			$customer['password_hash'] = md5($password);
		}
		try {
			$this->initSoap();
			$output = $this->client->call($this->_api_session_id, 'customer.update', array($customer_id, $customer));
		} catch (Exception $e) {
dd($e);
		}
		return $output;
	}

	/*
		Function: updateCustomerPassword
	*/
	function updateCustomerPassword($customer_id, $password) {
		$customer = array('password_hash' => md5($password));
		try {
			$this->initSoap();
			$output = $this->client->call($this->_api_session_id, 'customer.setPassword', array($customer_id, $password));
		} catch (Exception $e) {
dd($e);
		}
		return $output;
	}

	/*
		Function: createCustomer
			Creates a customer in the Magento database.

		Arguments:
			first - The first name for the new customer.
			last - The last name for the new customer.
			email - The email address for the new customer.
			password - The desired password for the new customer.

		Returns: int
	*/
	function createCustomer($first, $last, $email, $password) {
		$newCustomer = array(
	    	'firstname'  => $first,
	    	'lastname'   => $last,
	    	'email'      => $email,
	   		'password'   => $password,
	   		'group_id'	 => Cts_Registry::get('magento_default_group_id'),
	    	'store_id'   => Cts_Registry::get('magento_store_id'),
	    	'website_id' => Cts_Registry::get('magento_wesbite_id')
		);
		try {
			$this->initSoap();
			$output = $this->client->call($this->_api_session_id, 'customer.create', array($newCustomer));
		} catch (Exception $e) {
dd($e);
		}
		return $output;
	}

	/*
		Function: getRegionList
			Gets a list of regions from the Magento database.

		Arguments:
			country_code - The code of the country for which to retrieve a list of regions.

		Returns:
			An array with a list of regions or an empty array.
			If an empty array is returned, there is a problem with the Magento integration.
	*/
	function getRegionList($country_code) {
		$this->initSoap();
		$regions_all = $this->client->call($this->_api_session_id, 'region.list', $country_code);

		$regions = array();
		foreach ($regions_all as $region) {
			$regions[$region['code']] = $region['region_id'];
		}

		return $regions;
	}

	/*
		Function: createAddress
			Creates an address in the Magento database.

		Arguments:
			customer_id - The ID of the customer to add the address to.
			address - The address data to use for the new address.

		Returns:
			TBD
	*/
	function createAddress($customer_id, $address) {
		$errors = 0;			

		$newCustomerAddress = array(
			'firstname'  => $address['first_name'],
		    'lastname'   => $address['last_name'],					
		    'city'       => $address['city'],
		    'street'     => array($address['address_1'],$address['address_2']),
		    'telephone'  => $address['phone'],
		    'postcode'   => $address['zip'],
		    'is_default_billing'  => true,
		    'is_default_shipping' => true
		);

		$regionList = $this->getRegionList("US");

		if (array_key_exists($address['state'], $regionList)) {
			$newCustomerAddress['region_id'] = $regionList[$address['state']];
			$newCustomerAddress['region'] = $address['state'];
			$newCustomerAddress['country_id'] = "USA";
		} else {
			$errors++;
		}
		
		if (is_null($newCustomerAddress['firstname'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['lastname'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['city'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['street'][0])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['telephone'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['postcode'])) {
			$errors++;
		}

		if ($errors == 0) {
			$this->initSoap();
			return $this->client->call($this->_api_session_id, 'customer_address.create', array($customer_id, $newCustomerAddress));
		} else {
			return null;
		}
	}

	/*
		Function: updateAddress
			Updates an address in the Magento database.

		Arguments:
			address_id - The ID of the address to update.
			address - The new address information.

		Returns:
			TBD
	*/
	function updateAddress($address_id, $address) {
		$errors = 0;

		$newCustomerAddress = array(
			'firstname'  => $address['first_name'],
		    'lastname'   => $address['last_name'],
		    'city'       => $address['city'],
		    'street'     => array($address['address_1'],$address['address_2']),
		    'telephone'  => $address['phone'],
		    'postcode'   => $address['zip'],
		    'is_default_billing'  => true,
		    'is_default_shipping' => true
		);

		$regionList = $this->getRegionList("US");

		if (array_key_exists($address['state'],$regionList)) {
			$newCustomerAddress['region_id'] = $regionList[$address['state']];
			$newCustomerAddress['region'] = $address['state'];
			$newCustomerAddress['country_id'] = "USA";
		} else {
			$errors++;
		}

		if (is_null($newCustomerAddress['firstname'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['lastname'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['city'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['street'][0])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['telephone'])) {
			$errors++;
		}

		if (is_null($newCustomerAddress['postcode'])) {
			$errors++;
		}

		if($errors == 0){
			$this->initSoap();
			return $this->client->call($this->_api_session_id, 'customer_address.update', array($address_id, $newCustomerAddress));
		} else {
			return null;
		}
	}

	/*
		Function: getAddressList
			Gets a list of addresses from the Magento database for a particular customer.

		Arguments:
			customer_id - The ID of the customer for which to retrieve a list of addresses.

		Returns:
			An array of addresses, or null.
	*/
	function getAddressList($customer_id) {
		$this->initSoap();
		$result = $this->client->call($this->_api_session_id, 'customer_address.list', $customer_id);
		if (count($result) > 0) {
			return $result;
		} else {
			return null;
		}
	}

}
